package com.train.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
/**
 * 代理
 * */
public class CglibProxy implements MethodInterceptor {
    private Object star;
    public CglibProxy(Object star){
        this.star = star;
    }
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        // 无侵入式编程，既让程序执行了我们希望的逻辑，又不污染原程序逻辑
        if (method.getName().equals("sing")){
            System.out.println("唱此曲需要90w");
        }
        return method.invoke(star,args);
    }
    public Object getTargetProxy(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(star.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
}
